package bounjour;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

public class Field extends IObjectFactory {

	private int id;
	public int getID() { return id; }

	private int postID;
	public int getPostID() { return postID; }

	private FieldType type;
	public FieldType getType() { return type; }
	public void setType(FieldType value) { type = value; }
	
	private String label = "";
	public String getLabel() { return label; }
	public void setLabel(String value) { label = value; }

	private String[] values;
	public String[] getValues() {
		return values;
	}
	
	public void setValues(String[] value) {
		values = value;
	}
	
	public String getValuesString() {
		if (values != null && values.length > 0) {
			StringBuffer sb = new StringBuffer();
			sb.append(values[0]);
			for (int i=1; i<values.length; i++) sb.append(","+values[i]);
			return sb.toString();
		}
		return "";
	}
	
	
	
	public Field() {}
	
	public Field(int postID) {
		this.postID = postID;
	}
	
	public void buildFromReader(java.sql.ResultSet RS) {
		try {
			this.id = RS.getInt("ID");
			this.postID = RS.getInt("PostID");
			this.label = RS.getString("Label");
			this.type = FieldType.values()[RS.getInt("Type")];
			try{
				this.values = RS.getString("Values").split(",");
			}catch(Exception e0){}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void save() {
		Connection cn = null;
		java.sql.PreparedStatement ps = null;
		
	    try{
	    	cn = getConnection();
	    	if (this.id == 0) { // create	    		
			    ps = cn.prepareStatement("INSERT INTO PostForm (`PostID`,`Label`,`Type`,`Values`) VALUES (?,?,?,?);", Statement.RETURN_GENERATED_KEYS);
			    ps.setInt(1, this.getPostID());
			    ps.setString(2, this.getLabel());
			    ps.setInt(3, this.getType().ordinal());
			    ps.setString(4,  this.getValuesString());
			    
			    ps.execute();
			    ResultSet rs = ps.getGeneratedKeys();
			    if (rs.next()) this.id = rs.getInt(1);
			    rs.close();
	    	}
	    	else { // update
	    		ps = cn.prepareStatement("UPDATE PostForm SET `Label`=?,`Type`=?,`Values`=? WHERE `ID`=?");
	    		ps.setString(1, this.getLabel());
			    ps.setInt(2, this.getType().ordinal());
			    ps.setString(3,  this.getValuesString());
			    ps.execute();
	    	}
	    	cn.close();
	    	ps.close();
	    }
	    catch (Exception sqlEx){
	      System.err.println(sqlEx);
	    }			
	}
	
	static public List<Field> getFields(int postID) {
		return getObjectList(Field.class, "SELECT * FROM PostForm WHERE PostID=? ORDER BY ID;", postID);
	}
	
	

}
